﻿using System;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using VirusCleaner.IPlugin.Plugin;


namespace VirusCleaner.Scanner
{
    public partial class ScannerControl : UserControl,IUiElement
    {
        
        private List<string> _list;
        private long _length = -1;
        private Thread _thread = null;
        /// <summary>
        /// 
        /// </summary>
        public ScannerControl()
        {
            InitializeComponent();
        }
        #region IUiElement 成员

        public int Init()
        {
            return 0;
        }

        public void Active(bool active)
        {
            if(_thread != null && _thread.ThreadState == ThreadState.Stopped)
                tabControlMain.SelectTab(0);
        }

        #endregion
        private void ScannerControl_Load(object sender, EventArgs e)
        {
            _list = new List<string>();
        }
        private void BtnFastScanClick(object sender, EventArgs e)
        {
            _list = new List<string>()
                        {
                            @"C:\Windows\System32\"
                        };
            Scanner();
        }
        private void BtnFullScanClick(object sender, EventArgs e)
        {
            _list = new List<string>();
            foreach (DriveInfo drive in DriveInfo.GetDrives())
            {
                if (drive.IsReady)
                {
                    _list.Add(drive.RootDirectory.FullName);
                }
            }
            Scanner();
        }
        private void BtnCustScanClick(object sender, EventArgs e)
        {
            _list = FolderView.Show();
            if (_list.Count > 0)
            {
                Scanner();
            }
        }
        private void BtnStopClick(object sender, EventArgs e)
        {

        }
        private void Scanner()
        {

			this.cListViewScan.Items.Clear();
            this.tabControlMain.SelectTab(1);
            progressBar1.Style = ProgressBarStyle.Marquee;
            this.lblState.Text = @"正在初始化环境...";
            _thread = new Thread(TotalSize);
            _thread.Start();

        }
        private void SearchAllFiles()
        {
            foreach (string str in _list)
            {
                SearchAllFiles(str);
            }
            Invoke(new Action<ScannerControl>(x =>
                                                  {
                                                      x.progressBar1.Value = x.progressBar1.Maximum;
                                                      x.lblState.Text = String.Format("任务已成功完成,发现 {0} 个威胁.",
                                                                                      cListViewScan.Items.Count);
                                                  }

                       ), this);
        }
        private void SearchAllFiles(string path)
        {
            try
            {
                foreach (string file in Directory.GetFiles(path))
                {
                    Invoke(new Action<string>(delegate(string x)
                    {
                        if (x == null)
                            throw new ArgumentNullException("X");

                        lblState.Text = x;
                        var fi = new FileInfo(x);
                        progressBar1.Value += Convert.ToInt32(fi.Length / 1000);
                        if (false || progressBar1.Value % 255 == 0)
                        {
                            Application.DoEvents();
                            var item = new ListViewItem("Trojan.Win32");
                            item.SubItems.Add(fi.Name);
                            item.SubItems.Add(x);
                            cListViewScan.Items.Add(item);
                        }
                    }), file);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            try
            {
                foreach (string str in Directory.GetDirectories(path))
                {
                    SearchAllFiles(str);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        
        private void TotalSize()
        {
            foreach (String str in _list)
            {
                //判断是否是驱动器
                if (str.Length == 3)
                {
                    var drive = new DriveInfo(str);
                    if (drive.IsReady)
                    {
                        _length += drive.TotalSize - drive.TotalFreeSpace;
                    }
                }
                else
                {
                    GetDirectorySize(str);
                }
            }

            Invoke(new Action<long>(delegate(long x)
            {
                lblState.Text = @"初始环境完成.";
                progressBar1.Style = ProgressBarStyle.Continuous;
                progressBar1.Maximum = Convert.ToInt32(x / 1000);
                progressBar1.Value = 0;
            }), _length);

            _thread = new Thread(SearchAllFiles);
            _thread.Start();
        }
        private void GetDirectorySize(string dir)
        {
            try
            {
                foreach (string file in Directory.GetFiles(dir))
                {
                    var fi = new FileInfo(file);
                    _length += fi.Length;
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
            }
            try
            {
                foreach (string directory in Directory.GetDirectories(dir))
                {
                    GetDirectorySize(directory);
                    
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        private void BtnReturnClick(object sender, EventArgs e)
        {
            tabControlMain.SelectTab(0);
        }

        #region IPlugin 成员

        public string PluginName
        {
            get { throw new NotImplementedException(); }
        }

        #endregion
    }
}
